<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        v-model="ruleForm.password"
        type="password"
        autocomplete="off"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        分配账号
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from "vue";
import { userReg } from "../../../service/api/user";
import { ElMessage } from "element-plus";

const ruleFormRef = ref();

//表单数据包
const ruleForm = reactive({
  username: "",
  password: "",
});

// 表单验证规则
const rules = reactive({
  username: [{ required: true, trigger: "blur" }],
  password: [{ required: true, trigger: "blur" }],
});

//表单提交事件
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      console.log("submit!"); //表单验证通过
      let msg = await userReg(ruleForm); //触发注册请求
      ElMessage(msg);
    } else {
      console.log("error submit!"); //表单验证失败
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
